<script lang="ts">
  import { useMutation } from "@sveltestack/svelte-query";

  const url = navigator.userAgent.includes("Windows")
    ? "https://customprotocol.test/example.html"
    : "customprotocol://test/example.html";

  let foo = "baz";
  let bar = "qux";
  let result = null;

  const mutation = useMutation(
    (newFooBar) =>
      fetch(url, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(newFooBar),
      })
        .then(function (response) {
          return response.json();
        })
        .then(function (myJson) {
          console.log("myJson=", myJson);
          return myJson;
        }),

    {
      onMutate: (variables) => {
        // A mutation is about to happen!

        // Optionally return a context containing data to use when for example rolling back
        return { id: 1 };
      },
      onError: (error, variables, context) => {
        // An error happened!
        console.log(`rolling back optimistic update with id ${context.id}`);
      },
      onSuccess: (data, variables, context) => {
        // Boom baby!
        console.log(
          "Boom baby! onSuccess, data=%s, variables=%s, context=%s",
          JSON.stringify(data),
          JSON.stringify(variables),
          JSON.stringify(context)
        );
      },
      onSettled: (data, error, variables, context) => {
        // Error or success... doesn't matter!
        console.log("I'm onSettled!");
      },
    }
  );
</script>

<div class="items-center px-5 py-8 mx-auto lg:px-24">
  <div class="flex flex-wrap mb-12 text-left">
    <input bind:value={foo} />
    <input bind:value={bar} />
    <button
      type="button"
      on:click={() => {
        const res = $mutation.mutate({ foo: foo, bar: bar });
      }}
    >
      Post it.
    </button>
    <p>
      aaaaaaaaaa:
      {$mutation.isLoading ? "useMutation loading ..." : $mutation.data || ""}
    </p>
    {#if $mutation.isLoading}
      <p>Adding FooBar...</p>
    {:else if $mutation.isError}
      <p>Error: {$mutation.error.message}</p>
    {:else if $mutation.isSuccess}
      <p>FooBar Added Successfully! Result:</p>
      {$mutation.data}
    {:else}
      <h1>
        Click `Post it` to create FooBar using async-graphql+customprotocol
      </h1>
    {/if}
  </div>
</div>
